package five_LongestCommonPrefix;

public class CSolution {

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"aa", "aac", "aab"}));
        System.out.println(longestCommonPrefix(new String[]{"aa", "", "aab"}));
        System.out.println(longestCommonPrefix(new String[]{"aa", "a", "aab"}));
        System.out.println(longestCommonPrefix(new String[]{"aa", "abcd", "aab"}));
    }

    private static String longestCommonPrefix(String[] strs) {
        //数组长度可以为0
        if (strs == null || strs.length == 0) {
            return "";
        }
        String flagStr = strs[0];
        if (strs.length == 1) {
            return flagStr;
        }
        for (int index = 0; index < flagStr.length(); index++) {
            for (int i = 1; i < strs.length; i++) {
                if (strs[i] == null || strs[i].equals("")) {
                    return "";
                }
                if (index >= strs[i].length()) {
                    return flagStr.substring(0, index);
                }
                if (strs[i].charAt(index) != flagStr.charAt(index)) {
                    return flagStr.substring(0, index);
                }
            }
        }
        return flagStr;
    }
}
